package wty.web.projgen.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import wty.web.projgen.dao.DefaultDAO;
import wty.web.projgen.view.Command;

@Controller
@RequestMapping("/")
public class ProjgenController {
	private DefaultDAO defaultDAO = new DefaultDAO();
	
	@RequestMapping(method=RequestMethod.GET)
	public String index(Model model) {
		Command command = new Command();
		command.setUsers(defaultDAO.getUsers());
		model.addAttribute(command);
		return "projgen/index";
	}
	
	@RequestMapping(method=RequestMethod.POST)
	public String index(Command command, BindingResult bindingResult, Model model) {
		if(bindingResult.hasErrors()) {
			System.out.println("Error!!");
			for(FieldError err:bindingResult.getFieldErrors()) {
				System.out.println(err.getField());
			}
			model.addAttribute("errs", bindingResult.getFieldErrors());
		} else {
			defaultDAO.setUsers(command.getUsers());
		}
		model.addAttribute(command);
		return "projgen/index";
	}
}
